package com.spx.chapter06;

import com.spx.chapter05.pojo.Event;
import com.spx.util.SampleDataUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.*;

/**
 * create by undeRdoG on  2022-05-02  21:12
 * 凡心所向，素履以往，生如逆旅，一苇以航。
 */
public class ProcessWindowFunctionTest {

    public static void main(String[] args) throws Exception {

        /*
        *   统计 1000ms 内，每个用户访问的时间的中位数
        * */
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        SingleOutputStreamOperator<Event> dataSource = env.fromCollection(SampleDataUtil.getSample())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<Event>forBoundedOutOfOrderness(Duration.ofMillis(1L))
                                .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                                    @Override
                                    public long extractTimestamp(Event element, long recordTimestamp) {
                                        return element.timestamp;
                                    }
                                })
                );

        WindowedStream<Event, String, TimeWindow> window = dataSource.keyBy(data -> data.user)
                .window(TumblingEventTimeWindows.of(Time.milliseconds(1000L)));


        SingleOutputStreamOperator<Tuple2<String, Long>> res = window.process(new MyProcessWindowFunction());

        res.print();

        env.execute();

    }


    public static class MyProcessWindowFunction extends ProcessWindowFunction<Event, Tuple2<String,Long>,String,TimeWindow>{

        // 求取中为数字

        @Override
        public void process(String key, Context context, Iterable<Event> iterable, Collector<Tuple2<String, Long>> collector) throws Exception {
            List<Event> list = new ArrayList<>();
            Iterator<Event> iterator = iterable.iterator();
            while (iterator.hasNext()){
                list.add(iterator.next());
            }

            Collections.sort(list, new Comparator<Event>() {
                @Override
                public int compare(Event o1, Event o2) {
                    if (o1.timestamp.equals(o2.timestamp)){
                        return 0;
                    }else if (o1.timestamp < o2.timestamp){
                        return -1;
                    }else{
                        return 1;
                    }
                }
            });

            Long res;
            if (list.size() % 2 == 1){
                res = list.get(list.size() / 2).timestamp;
            }else{
                res = (list.get(list.size() / 2).timestamp + list.get(list.size() / 2 - 1).timestamp) / 2;
            }

            Long start = context.window().getStart();
            Long end = context.window().getEnd();

            collector.collect(Tuple2.of("window is " + start + "~" + end + " " +key, res));

        }
    }
}
